package net.example.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import net.example.model.GGGroup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class GGGroupPersister {
    private static GGGroupPersister instance =new GGGroupPersister();
    private GGGroupPersister(){}
    public static GGGroupPersister getInstance() {
        return instance;
    }

    public List<GGGroup> getAll()
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();
        ArrayList<GGGroup> list = new ArrayList<GGGroup>();
        Cursor cursor = db.query(DatabaseHelper.GGGroup,
                new String[]{"GroupID", "Name", "CreatorID", "Announce",
                        "Members","IsPrivate", "CreateTime", "Version"},
                null, null, null, null, null);
        while (cursor.moveToNext()) {
            GGGroup group = new GGGroup();
            group.setGroupID(cursor.getString(cursor.getColumnIndex("GroupID")));
            group.setName(cursor.getString(cursor.getColumnIndex("Name")));
            group.setCreatorID(cursor.getString(cursor.getColumnIndex("CreatorID")));
            group.setMembers(cursor.getString(cursor.getColumnIndex("Members")));
            group.IsPrivate= cursor.getInt(cursor.getColumnIndex("IsPrivate"))==1 ;
            group.setCreateTime(new Date(cursor.getLong(cursor.getColumnIndex("CreateTime"))));
            group.setAnnounce(cursor.getString(cursor.getColumnIndex("Announce")));
            group.setVersion(cursor.getInt(cursor.getColumnIndex("Version")));
            list.add(group);
        }
        cursor.close();//关闭结果集
        db.close();//关闭数据库对象
        return list;
    }

    public void delete(String groupID)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        db.delete(DatabaseHelper.GGGroup, "GroupID=?", new String[]{groupID});
        db.close();//关闭数据库对象
    }

    public void insert(GGGroup GGGroup)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("GroupID", GGGroup.getGroupID());
        values.put("Name", GGGroup.getName());
        values.put("CreatorID", GGGroup.getCreatorID());
        values.put("Announce", GGGroup.getAnnounce());
        values.put("Members", GGGroup.getMembers());
        values.put("IsPrivate", GGGroup.IsPrivate);
        values.put("CreateTime", GGGroup.getCreateTime().getTime());
        values.put("Version", GGGroup.getVersion());

        //调用方法插入数据
        db.insert(DatabaseHelper.GGGroup, "Name", values);
        db.close();
    }
}
